package com.world.cat.app.utils;

import com.world.cat.service.sys.RoleResourceService;
import com.world.cat.service.sys.security.MySecurityMetadataSource;
import com.world.common.util.SysUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Iterator;

/**
 * URL请求资源判断
 */
public class PrivilegeVerifierUtil {
    private static final Logger logger = LoggerFactory.getLogger(PrivilegeVerifierUtil.class);

    public static String getPrivilegeValue(HttpServletRequest request) {
        String privilegeValue = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (contextPath != null && contextPath.length() > 0) {
            privilegeValue = privilegeValue.substring(contextPath.length());
        }
        //sso重定向过来会带这个
        int jsessionPosition = privilegeValue.indexOf(";jsession");
        if (jsessionPosition > -1) {
            privilegeValue = privilegeValue.substring(0, privilegeValue.indexOf(";jsession"));
        }
        if ("/".equals(privilegeValue)) {
            return null;
        }

        return privilegeValue;
    }

    public static boolean verifier(String userName, String privilegeValue) {
        if (SysUtil.isEmpty(privilegeValue)) {
            return true;
        }
        boolean hasThisPermission = false;
        Collection<ConfigAttribute> configAttributes = MySecurityMetadataSource.resourceMap.get(privilegeValue);
        if (configAttributes == null) {
            //属于被控制的资源，但是没有角色选择这个资源，默认便是谁也没有这个资源的权限
            if (RoleResourceService.urlNameMap.containsKey(privilegeValue)) {
                return false;
            }
            return true;
        }
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute configAttribute = iterator.next();
            String needPermission = configAttribute.getAttribute();
            UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            for (GrantedAuthority ga : userDetails.getAuthorities()) {
                if (needPermission.equals(ga.getAuthority())) {
                    return true;
                }
            }
        }
        if (!hasThisPermission) {
            logger.debug("[userName:{}] doesn't have the request permission of  \"{}\"", userName, privilegeValue);
        } else {
            logger.debug("[userName:{}] has the request permission of  \"{}\"", userName, privilegeValue);
        }
        return hasThisPermission;
    }
}
